<template>
  <el-header class="customHeader fixed-header">
    <div class="topBar"></div>
    <div class="headerContent">
      <!-- 左侧：Logo + 分隔线 + 标题 -->
      <div class="headerLeft">
        <img src="@/assets/image/logo.jpg" class="logo" />
        <div class="headerDivider"></div>
        <div class="titleWrapper">
          <div class="mainTitle">讯航<span class="newsText">News</span></div>
          <div class="subTitle">——武大新闻整合平台</div>
        </div>
        <el-button type="primary" size="large" class="aiChatBtn" @click="$router.push('/ai')">
          AI Chat
        </el-button>

      </div>

      <div class="headerRightGroup">
        <!-- 右侧：搜索框 -->

        <div class="headerRight">
          <el-input v-model="searchText" placeholder="文章搜索" class="searchInput" clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button class="custom-search-btn" @click="handleSearch">
                <!-- 搜索逻辑待写 -->
                <img src="@/assets/image/搜索.png" class="search-icon" alt="搜索" />
              </el-button>
            </template>
          </el-input>
        </div>

        <!-- 新增管理员区域 -->
        <div class="adminArea">
          <el-button type="primary" size="large" class="adminBtn" @click="$router.push('/admin')">
            管理员登录
          </el-button>
          <img src="@/assets/image/admin.png" class="adminLogo" />
        </div>
      </div>
    </div>
  </el-header>
  <div class="search-container">
    <!-- 搜索头部 -->
    <div class="search-header">
      <h2>搜索结果</h2>
      <p v-if="searchKey">搜索关键词: "{{ searchKey }}"</p>
      <p v-else>请输入搜索关键词</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      正在加载搜索结果...
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">
      <el-alert :title="error" type="error" show-icon />
    </div>

    <!-- 搜索结果 -->
    <div v-else>
      <!-- 无结果提示 -->
      <div v-if="!newsData.length" class="no-result">
        <el-empty description="没有找到相关新闻" />
      </div>

      <div class="newsContainer">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 搜索结果新闻卡片列表 -->
        <div v-else class="news-list">
          <div v-for="item in newsData" :key="item.id" class="news-item" @click="intoDetailPage(item.id)">
            <div class="news-image">
              <img :src="item.images" :alt="item.title" v-if="item.images" />
              <div class="no-image" v-else>暂无图片</div>
            </div>
            <div class="news-content">
              <h3>{{ item.title }}</h3>
              <p class="summary">{{ item.summary }}</p>
              <div class="meta">
                <span class="author">{{ item.author }}</span>
                <span class="date">{{ formatDate(item.submitTime) }}</span>
                <span class="views">浏览: {{ item.pageviews }}次</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 1">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total * pageSize"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

onMounted(() => {
  if (searchKey.value) {
    fetchSearchResults()
  }
})

// 路由信息
const router = useRouter()
const route = useRoute()
const searchKey = ref(route.query.key || '')

//关键词模糊搜索
const searchText = ref('')
const handleSearch = () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  router.push({
    path: '/search',
    query: {
      key: searchText.value
    }
  })
}


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10) // 每页显示数量
const total = ref(0) // 总页数

// 数据相关
const newsData = ref([])
const loading = ref(false)
const error = ref('')
const intoDetailPage=async (item) => {
  try{
    console.log('item',item)
    await router.push({
      path: '/HomePage/DetailPage', query: {id: item,
      }
    })}
  catch (err){
    error.value = err.response?.data?.message || '失败'
  }
}
// 获取搜索结果
const fetchSearchResults = async () => {
  if (!searchKey.value) return

  loading.value = true
  error.value = ''

  try {
    const response = await fetch(
      `http://localhost:8080/news/search?key=${encodeURIComponent(searchKey.value)}&current=${currentPage.value}`,
    )

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`)
    }

    const data = await response.json()

    if (data.success) {
      newsData.value = data.data
      total.value = data.total
    } else {
      throw new Error('获取数据失败')
    }
  } catch (err) {
    error.value = err.message
    ElMessage.error('搜索失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchSearchResults()
}

// 监听路由变化
watch(
  () => route.query.key,
  (newKey) => {
    searchKey.value = newKey || ''
    searchText.value = newKey || '' // 同步到搜索框
    currentPage.value = 1
    fetchSearchResults()
  },
  { immediate: true },
)
</script>

<style scoped>
/* 新闻卡片样式 */
.news-item {
  /* 确保图片不会变形 */
  .news-image img {
    width: 100%;
    height: 180px;
    object-fit: cover;
  }

  .news-content {
    .summary {
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }
}
.search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  margin-bottom: 30px;
  text-align: center;
}

.search-header h2 {
  color: #333;
  margin-bottom: 10px;
}

.loading {
  text-align: center;
  padding: 40px;
  font-size: 16px;
}

.loading .el-icon {
  margin-right: 10px;
  animation: rotating 2s linear infinite;
}

.error {
  margin: 20px 0;
}

.no-result {
  padding: 50px 0;
  text-align: center;
}

.newsContainer {
  width: 90%;
  margin: 0 auto;
  padding: 1.25rem;
}

.news-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.news-item {
  display: flex; /* 改为横向排列 */
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.news-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.news-image {
  flex: 0 0 30%; /* 图片占30%宽度 */
  height: 180px; /* 固定高度 */
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.news-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.no-image {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.news-content {
  flex: 1; /* 内容占剩余70% */
  padding: 15px;
}

.news-content h3 {
  margin: 0 0 10px;
  font-size: 18px;
  color: #222;
  line-height: 1.4;
}

.summary {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #888;
}

.meta .author {
  flex: 1;
}

.meta .time {
  margin: 0 10px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/*

————————————————————————————————————————————————————————————————————————————————————————标题样式——————————————————————————————————————————————————————————————————————————————

 */

/* 固定头部样式 */
.fixed-header {
  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在最上层 */
  width: 100% !important;
}

/* 占位元素样式 (根据您实际的header高度调整) */
.header-placeholder {
  height: 8.125rem; /* topBar(1.875rem) + headerContent(6.25rem) */
}

/* 标题区域样式 */
.customHeader {
  background-color: #ffffff; /* 背景眼色 */
  color: rgb(7, 0, 0); /* 文字颜色 */
  padding: 0 1.25rem;
  height: 7.5rem;
  display: flex;
  align-items: center;
  flex-direction: column; /* 改为垂直布局 */
  box-shadow:
    0 0.25rem 0.5rem rgba(0, 0, 0, 0.1),
    0 0.5rem 1rem rgba(0, 0, 0, 0.1),
    0 0.75rem 1.5rem rgba(0, 0, 0, 0.1);
  /* 多层叠加阴影，营造立体感 */
}

/* 标题内容样式 */
.headerContent {
  width: 100%;
  display: flex;
  justify-content: space-between; /* 改为左右布局 */
  align-items: center;
}

/* logo样式 */
.logo {
  height: 5rem;
  width: auto;
  object-fit: contain;
}

/* 标题容器 */
.titleWrapper {
  display: flex;
  flex-direction: column;
}

/* 主标题样式 */
.mainTitle {
  font-size: 2.5rem;
  font-weight: bold;
  color: #000;
}

/* News文字样式 */
.newsText {
  margin-left: 0.3125rem;
}

/* 副标题样式 */
.subTitle {
  font-size: 1.25rem;
  color: #409eff; /* Element Plus 主蓝色 */
}

/* 分割线 */
.headerDivider {
  height: 5rem;
  width: 0.0625rem;
  background-color: #c9d5f1;
}

/* 新增左侧容器 */
.headerLeft {
  display: flex;
  align-items: center;
  gap: 0.9375rem;
}

/* 右侧搜索框样式 */
.headerRight {
  width: 17.5rem;
  margin-left: auto;
}

/* 输入框样式 */
.searchInput {
  :deep(.el-input__inner) {
    height: 2.5rem;
    line-height: 2.5rem;
    font-size: 1rem;
    padding: 0 0.9375rem;
    /* 确保输入区域可点击 */
    pointer-events: auto;
    cursor: text;
  }

  :deep(.el-input__wrapper) {
    /* 移除可能遮挡的样式 */
    overflow: visible;
  }
}

.search-icon {
  width: 1.25rem;
  height: 1.25rem;
  object-fit: contain;
}

.headerRightGroup {
  display: flex;
  align-items: center;
  gap: 1.25rem;
}

/* 管理员区域样式优化 */
.adminArea {
  display: flex;
  align-items: center;
  gap: 0.5rem; /* 缩小间距 */
  margin-left: 0.9375rem; /* 与搜索框的间距 */
}

/* 管理员按钮样式优化 */
.adminBtn {
  font-size: 1.125rem; /* 调整为0.875rem */
  font-weight: 600; /* 加粗 */
  letter-spacing: normal;
  padding: 0.4375rem 0.9375rem; /* 缩小内边距 */
  border-radius: 0.25rem;
  background-color: #3589dc; /* Element主色 */
  color: white;
  transition: all 0.3s;
}

.aiChatBtn {
  font-size: 1.125rem; /* 调整为0.875rem */
  font-weight: 600; /* 加粗 */
  letter-spacing: normal;
  padding: 0.4375rem 0.9375rem; /* 缩小内边距 */
  border-radius: 0.25rem;
  background-color: #3589dc; /* Element主色 */
  color: white;
  transition: all 0.3s;
}

.adminBtn:hover {
  background-color: #66b1ff; /* 悬停颜色 */
  transform: translateY(-0.0625rem); /* 轻微上浮效果 */
}

/* 管理员Logo样式优化 */
.adminLogo {
  width: 1.75rem;
  height: 1.75rem;
  object-fit: contain;
  border-radius: 50%; /* 圆形Logo */
  border: 0.0625rem solid #e6e6e6; /* 浅色边框 */
  padding: 0.125rem; /* 内边距 */
  background-color: white; /* 白色背景 */
  box-shadow: 0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.1); /* 轻微阴影 */
}
</style>
